package com.lxl.microservicesimleconsumermovie.controller;

import com.lxl.microservicesimleconsumermovie.entity.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;


/**
 * @desc: Movie controller
 * @author: lxl
 * @date: 2018/11/9 16:01
 * @version: v1.0
 */
@RestController
public class MovieController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    /**
     * @desc: 从用户服务获得信息
     * @author: lxl
     * @date: 2018/11/15 9:55
     * @version: v1.0
     */
    @HystrixCommand(fallbackMethod = "findByIdFallback", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000"),
            @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000")
    }, threadPoolProperties = {
            @HystrixProperty(name = "coreSize", value = "1"),
            @HystrixProperty(name = "maxQueueSize", value = "10")
    })
    @GetMapping("/user/{id}")
    public User findById(@PathVariable Long id) {
        return this.restTemplate.getForObject("http://microservice-provider-user-my-metadata/" + id, User.class);
    }

    /**
     * @desc: 获取指定服务的元数据
     * @author: lxl
     * @date: 2018/11/15 9:54
     * @version: v1.0
     */
    @GetMapping("/user-instance")
    public List<ServiceInstance> showInfo() {
        ServiceInstance instance = this.loadBalancerClient.choose("microservice-provider-user-my-metadata");
        if (instance != null) {
            logger.info("{}:{}:{}", instance.getServiceId(), instance.getHost(), instance.getPort());
        }
        return this.discoveryClient.getInstances("microservice-provider-user-my-metadata");
    }

    /**
     * 断路器回退方法
     *
     * @param id 用户id
     * @return User
     */
    public User findByIdFallback(Long id) {
        User user = new User();
        user.setName("我是断路器回退方法");
        return user;
    }

    @GetMapping("/sidecar/test")
    public String sidecarFindById(){
        return this.restTemplate.getForObject("http://sidecar/", String.class);
    }
}
